// pages/terminal/chart/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js")
const wxCharts = require("../../../utils/wxcharts.js"), 
commonJs = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading:true,
    deviceNum:'',
    deviceId:0,
    categories:[],
    wenduData:[],
    nowDate:'',
    beginTime:'',
    endTime:'',
    isShowPop:false,
    currentDate: new Date().getTime(),
    minDate: new Date(2018, 0, 1).getTime(),
    currentTimeMin:'00:00',
    currentTimeMax:'23:59',
    nodeCount:1,
    nodeIndex:1,
    insIndex:0,
    nodeList:['节点1'],
    insList:['第1路电流设备','第2路电流设备'],
    nodeName:'节点1',
    insName:'第1路电流设备',
    isShowPopNode:false,
    isShowPopIns:false,
    nodeTempList:[],
    canvasImg:[],
    isShowPopMin:false,
    isShowPopMax:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.deviceId = parseInt(options.id)
    this.data.deviceNum = options.num;
    this.data.nodeCount = parseInt(options.node_count)
    console.log('currentDate',this.data.currentDate)
    var ss = commonJs.formatTimeSimple(new Date());
    console.log('ss',ss)
    for(var index in this.data.nodeCount){
      this.data.nodeList.push('节点' + (index + 1))
    }

    var date = new Date();
    //年 getFullYear()：四位数字返回年份
    var year = date.getFullYear(); //getFullYear()代替getYear()
    //月 getMonth()：0 ~ 11
    var month = date.getMonth() + 1;
    //日 getDate()：(1 ~ 31)
    var day = date.getDate();
    //时 getHours()：(0 ~ 23)
    var hour = date.getHours();
    //分 getMinutes()： (0 ~ 59)
    var minute = date.getMinutes();
    //秒 getSeconds()：(0 ~ 59)
    var second = date.getSeconds();

    var minHour = 0;
    if(hour == 0){
      minHour = 0;
    }else{
      minHour = hour - 1;
    }
    var maxHour = hour;

    var hourBeginStr = minHour < 10 ? '0' + minHour : minHour;
    hourBeginStr += ':00';
    var hourEndStr = maxHour < 10 ? '0' + maxHour : maxHour;
    hourEndStr += ':59';

    this.data.currentTimeMin = hourBeginStr
    this.data.currentTimeMax = hourEndStr

    this.setData({
      currentTimeMin: hourBeginStr,
      currentTimeMax: hourEndStr,
    })

    console.log('nodeList',this.data.nodeList)
    this.data.nowDate = ss;
    this.setData({
      deviceNum:this.data.deviceNum,
      nowDate: ss,
      nodeList: this.data.nodeList
    })
    this.onHttpInit(ss);
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function (date) {
    var that = this
    that.setData({ isLoading: true})
    fetchApi.httpPost('/device/wenduList', {
      device_id:that.data.deviceId,
      date: that.data.nowDate,
      beginHour: that.data.currentTimeMin,
      endHour: that.data.currentTimeMax,
      nodeIndex: that.data.nodeIndex,
      insIndex: that.data.insIndex,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        that.data.nodeTempList = res.data.data;
        that.setData({
          nodeTempList:  res.data.data
        })
        that.data.canvasImg = [];
        that.getMothElectro();
      }
      that.setData({  isLoading: false, loading: true, netWork: true,  })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  // 需要让 弹窗等 出现在canvas上的事件
  handleCanvarToImg(index) {
    var that = this;
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
      console.log('index',index)
      var count = this.data.nodeTempList.length;
      console.log('count',count)
      var id = 'yueEle_' + index;
      if(index < count){
        console.log('index',index + '存在,执行')
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: windowWidth,
          height: 200,
          canvasId: id,
          complete: function(res) {
            console.log( id, id)
            that.data.nodeTempList[index].canvasImg = res.tempFilePath
            that.data.nodeTempList[index].canvasWidth = windowWidth
            that.data.nodeTempList[index].canvasHeight = 200;
            that.data.canvasImg.push(res.tempFilePath)
            that.setData({ 
              canvasImg:that.data.canvasImg,
              nodeTempList:  that.data.nodeTempList
            });
            console.log('that.data.nodeTempList',that.data.nodeTempList)
            index++;
            that.handleCanvarToImg(index)
          }
        });
      }
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
  },
  getMothElectro:function(){
    var windowWidth = 320;
    var that  = this
    try {
     var res = wx.getSystemInfoSync();
     windowWidth = res.windowWidth;
    } catch (e) {
     console.error('getSystemInfoSync failed!');
    }
    
    if(this.data.nodeTempList.length > 0){
      this.data.nowDate = this.data.nodeTempList[0].day;
      this.data.currentTimeMin = this.data.nodeTempList[0].beginHour;
      this.data.currentTimeMax = this.data.nodeTempList[0].endHour;
  
      that.setData({
        nowDate: this.data.nodeTempList[0].day,
        currentTimeMin: this.data.nodeTempList[0].beginHour,
        currentTimeMax: this.data.nodeTempList[0].endHour,
      })
    }
    
    for(var index in this.data.nodeTempList){
      var categories = this.data.nodeTempList[index].times;
			var wenduData = this.data.nodeTempList[index].values;
			if(categories.length > 0){
				var yuelineChart = new wxCharts({ //当月用电折线图配置
					canvasId: 'yueEle_' + index,
					type: 'line',
					categories:categories, //categories X轴
					animation: true,
					// background: '#f5f5f5',
					series: [{
					 name: that.data.nodeTempList[index].data_title,//温度',
					 //data: yuesimulationData.data,
					 data:wenduData,
					 format: function (val, name) {
						return val.toFixed(2) + that.data.nodeTempList[index].data_unit;
					 }
					}, 
				 ],
					xAxis: {
						 //x轴旋转
						axisLabel: {
							interval: 0, //隔几项显示一个标签
							rotate: "45" //标签倾斜的角度，旋转的角度是-90到90度
						},
						disableGrid: true ,
						// axisLabel: {
						//   rotate:0 , 
						//   interval: 0,//横轴全部显示
						//   format: function (val) {
						//     return val.split('').join('\n')
						//    },
						// },
					},
					yAxis: {
					 title: that.data.nodeTempList[index].data_title + '('+that.data.nodeTempList[index].data_unit+')',  // '温度(℃)',
					 format: function (val) {
						return val.toFixed(2);
					 },
           min: 30,
           max:100,
           
					},
					width: windowWidth,
					height: 200,
					dataLabel: false,
					dataPointShape: true,
					extra: {  lineStyle: 'curve'  }
				});
			}
    }
    if(that.data.canvasImg.length == 0) {
      setTimeout(function(){
        that.data.canvasImg = [];
        that.handleCanvarToImg(0)
      },2000)
    }
   },
   onClickDate(){
     this.setData({
       isShowPop : !this.data.isShowPop
     })
   },
   onClickDateMin(){
     this.setData({
       isShowPopMin : !this.data.isShowPopMin
     })
   },
   onClickDateMax(){
     this.setData({
      isShowPopMax : !this.data.isShowPopMax
     })
   },
   onCancle(){
     var that = this;
    this.setData({
      isShowPop : false,
      nodeTempList: that.data.nodeTempList
    })
   },
   onCancleHour(e){
     console.log('onCancleHour',e)
     var that = this;
     var type = e.currentTarget.dataset.htype;
     if(type == 'min'){
       this.onClickDateMin();
     }else{
       this.onClickDateMax()
     }
    //  this.setData({
    //   isShowPopHour : false,
    //   nodeTempList: that.data.nodeTempList
    //  })
   },
   onConfirm(event){
    var that = this;
    for(var index in this.data.nodeTempList){
     that.data.nodeTempList[index].canvasImg = '';
     that.data.nodeTempList[index].canvasWidth = 0
     that.data.nodeTempList[index].canvasHeight = 0
     that.setData({ nodeTempList:  that.data.nodeTempList});
    }
     console.log('onConfirm',event)
     const { detail, currentTarget } = event;
     const result = this.getResult(detail, currentTarget.dataset.type);
     console.log('result',result)
     console.log('detail',detail)
     var ss = commonJs.formatTimeSimple(new Date(detail));
     that.data.nowDate = ss;
     this.setData({
      nowDate:ss,
       currentDate: detail,
       isShowPop:false
     })
     this.onHttpInit();
   },
   onConfirmHour(e){
    console.log('onConfirmHour',e)
    
    var type = e.currentTarget.dataset.htype;
    var time = e.detail;
    if(type == 'min'){
      this.data.currentTimeMin = time;
      this.setData({
        currentTimeMin:time
      })
      this.onClickDateMin();
    }else{
      this.data.currentTimeMax = time;
      this.setData({
        currentTimeMax:time
      })
      this.onClickDateMax()
    }
    this.onHttpInit();

   },
   getResult(time, type) {
     const date = new Date(time);
     switch (type) {
       case 'datetime':
         return date.toLocaleString();
       case 'date':
         return date.toLocaleDateString();
       case 'year-month':
         return `${date.getFullYear()}/${date.getMonth() + 1}`;
       case 'time':
         return time;
       default:
         return '';
     }
   },
   formatData(type, value) {
     if (type === 'year') {
       return `${value}年`;
     }
     if (type === 'month') {
       return `${value}月`;
     }
     return value;
   },
   touchHandler: function (e) { //当月用电触摸显示
    yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
     background: '#7cb5ec',
     format: function (item, category) {
      return category + '日 ' + item.name + ':' + item.data
     }
    });
   },
})